package com.osilon.updater.tasks;

import java.lang.reflect.Modifier;

import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.MethodNode;

import com.osilon.asm.InsnSearcher;
import com.osilon.asm.OsilonClassNode;
import com.osilon.util.ClassCache;

public class PropertiesTask extends Task {
	@Override
	public boolean canProcess(OsilonClassNode node) {
		return node.constants.get("server-ip") != null;
	}

	@Override
	public void process(ClassCache cache, OsilonClassNode node) {
		MethodNode mn = node.constants.get("server-ip").get(0);
		
		InsnSearcher searcher = new InsnSearcher(mn);
		searcher.nextLdc("server-ip");
		
		FieldInsnNode fin = searcher.prevFieldInsn(Opcodes.GETFIELD);
		OsilonClassNode n = cache.getClass(fin.desc.substring(1, fin.desc.length() - 1));
		n.interfaces.add("com/osilon/hooks/ServerProperties");
		node.addGetter("getServerProperties", "Lcom/osilon/hooks/ServerProperties;", fin.name, fin.desc);
	
		for(MethodNode m : n.public_methods) {
			if(m.desc.equals("(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;")) {
				n.addMethodDelegate("getString", m.desc, m.name, m.desc, Modifier.isPrivate(m.access));
			} else if(m.desc.equals("(Ljava/lang/String;Z)Z")) {
				n.addMethodDelegate("getBoolean", m.desc, m.name, m.desc, Modifier.isPrivate(m.access));
			} else if(m.desc.equals("(Ljava/lang/String;I)I")) {
				n.addMethodDelegate("getInt", m.desc, m.name, m.desc, Modifier.isPrivate(m.access));
			}
		}
	}
}
